<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <ContainerSearchForm
      v-show="showSearch"
      :query-params="queryParams"
      :warehouse-list="warehouseList"
      :project-list="projectList"
      @search="handleQuery"
      @reset="resetQuery"
    />

    <!-- 工具栏 -->
    <ContainerToolbar
      :single="single"
      :multiple="multiple"
      :show-search.sync="showSearch"
      @add="handleAdd"
      @update="handleUpdate"
      @delete="handleDelete"
      @export="handleExport"
      @bind-locator="handleBindLocator"
      @unbind-locator="handleUnbindLocator"
      @refresh="getList"
    />

    <!-- 数据表格 -->
    <ContainerTable
      :loading="loading"
      :container-list="containerList"
      @selection-change="handleSelectionChange"
      @detail="handleDetail"
      @update="handleUpdate"
      @delete="handleDelete"
    />

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改抽屉 -->
    <ContainerFormDrawer
      :visible.sync="open"
      :title="title"
      :form="form"
      :rules="rules"
      :project-list="projectList"
      :material-options="materialOptions"
      :filtered-material-options="filteredMaterialOptions"
      :project-warehouse-list="projectWarehouseList"
      :material-loading="materialLoading"
      @submit="submitForm"
      @cancel="cancel"
      @project-change="handleProjectChange"
      @material-code-change="handleMaterialCodeChange"
      @current-material-code-change="handleCurrentMaterialCodeChange"
    />

    <!-- 详情抽屉 -->
    <ContainerDetailDrawer
      :visible.sync="detailOpen"
      :detail-form="detailForm"
      :active-tab.sync="activeTab"
      :operation-list="operationList"
      :operation-total="operationTotal"
      :operation-loading="operationLoading"
      :operation-query-params="operationQueryParams"
      :transfer-list="transferList"
      :transfer-total="transferTotal"
      :transfer-loading="transferLoading"
      :transfer-query-params="transferQueryParams"
      :location-list="locationList"
      :location-total="locationTotal"
      :location-loading="locationLoading"
      :location-query-params="locationQueryParams"
      @open="handleDetailOpen"
      @tab-click="handleTabClick"
      @operation-pagination="getOperationList"
      @transfer-pagination="getTransferList"
      @location-pagination="getLocationList"
    />

    <!-- 绑定定位器对话框 -->
    <BindLocatorDialog
      :visible.sync="bindOpen"
      :bind-form="bindForm"
      :bind-rules="bindRules"
      :container-display-text="getContainerDisplayText()"
      :locator-search-text.sync="locatorSearchText"
      :filtered-locator-list="filteredLocatorList"
      :locator-loading="locatorLoading"
      @search="handleLocatorSearch"
      @filter="filterLocators"
      @submit="submitBindForm"
    />
  </div>
</template>

<script>
import {
  listContainer,
  getContainer,
  addContainer,
  updateContainer,
  delContainer,
  bindLocator,
  unbindLocator,
  batchBindLocators,
  exportContainer,
  listLocatorForBind,
  checkContainerCodeUnique,
  getProjectMaterials,
  getProjectWarehouses
} from '@/api/pack/container'
import { listWarehouse } from '@/api/pack/warehouse'
import { listProject } from '@/api/pack/project'
import {
  listOperationLog,
  listTransferRecord,
  listLocationLog
} from '@/api/pack/containerHistory'

// 导入子组件
import ContainerSearchForm from './components/ContainerSearchForm.vue'
import ContainerToolbar from './components/ContainerToolbar.vue'
import ContainerTable from './components/ContainerTable.vue'
import ContainerFormDrawer from './components/ContainerFormDrawer.vue'
import ContainerDetailDrawer from './components/ContainerDetailDrawer.vue'
import BindLocatorDialog from './components/BindLocatorDialog.vue'

export default {
  name: 'Container',
  components: {
    ContainerSearchForm,
    ContainerToolbar,
    ContainerTable,
    ContainerFormDrawer,
    ContainerDetailDrawer,
    BindLocatorDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 器具表格数据
      containerList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 是否显示绑定定位器对话框
      bindOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        containerCode: null,
        materialCode: null,
        companyId: null,
        currentWarehouseId: null,
        locationStatus: null,
        businessStatus: null,
        packingStatus: null,
        currentProjectId: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 绑定表单参数
      bindForm: {},
      // 当前活动的标签页
      activeTab: 'basic',
      // 操作记录相关
      operationList: [],
      operationTotal: 0,
      operationLoading: false,
      operationQueryParams: {
        pageNum: 1,
        pageSize: 10,
        containerId: null
      },
      // 移库记录相关
      transferList: [],
      transferTotal: 0,
      transferLoading: false,
      transferQueryParams: {
        pageNum: 1,
        pageSize: 10,
        containerId: null
      },
      // 定位日志相关
      locationList: [],
      locationTotal: 0,
      locationLoading: false,
      locationQueryParams: {
        pageNum: 1,
        pageSize: 10,
        containerId: null
      },
      // 仓库列表
      warehouseList: [],
      // 项目关联仓库列表
      projectWarehouseList: [],
      // 项目列表
      projectList: [],
      // 项目物料列表（器具信息）
      materialOptions: [],
      // 物料加载状态
      materialLoading: false,
      // 定位器列表
      locatorList: [],
      // 过滤后的定位器列表
      filteredLocatorList: [],
      // 定位器搜索文本
      locatorSearchText: '',
      // 定位器加载状态
      locatorLoading: false,
      // 表单校验
      rules: {
        containerCode: [
          { required: true, message: '器具流水号不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '器具流水号长度必须在1到100个字符之间', trigger: 'blur' }
        ],
        materialCode: [
          { required: true, message: '器具型号编码不能为空', trigger: 'change' }
        ],
        locationStatus: [
          { required: true, message: '位置状态不能为空', trigger: 'change' }
        ],
        businessStatus: [
          { required: true, message: '业务状态不能为空', trigger: 'change' }
        ]
      },
      // 绑定表单校验
      bindRules: {
        locatorIds: [
          { required: true, type: 'array', min: 1, message: '请至少选择一个定位器', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 根据用户选择的器具型号编码过滤物料列表
    filteredMaterialOptions() {
      if (!this.form.materialCode) {
        return [];
      }

      return this.materialOptions.filter(material =>
        material.containerMaterialCode === this.form.materialCode
      );
    }
  },
  created() {
    this.getList()
    this.getWarehouseList()
    this.getProjectList()
  },
  methods: {
    /** 查询器具列表 */
    getList() {
      this.loading = true
      listContainer(this.queryParams).then(response => {
        this.containerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouse({ status: '0' }).then(response => {
        this.warehouseList = response.rows || []
      })
    },
    /** 查询项目列表 */
    getProjectList() {
      listProject({ projectStatus: '1' }).then(response => {
        this.projectList = response.rows || []
      })
    },
    /** 项目选择变化处理 */
    handleProjectChange(projectId) {
      if (projectId) {
        const selectedProject = this.projectList.find(project => project.projectId === projectId)
        if (selectedProject) {
          this.form.companyId = selectedProject.companyId
          // 自动填充项目编码和名称
          this.form.currentProjectCode = selectedProject.projectCode
          this.form.currentProjectName = selectedProject.projectName
        }

        // 清空器具相关字段
        this.form.materialCode = null
        this.form.materialName = null
        this.materialOptions = []

        // 清空当前仓库
        this.form.currentWarehouseId = null

        // 清空当前物料信息
        this.form.currentMaterialCode = null
        this.form.currentMaterialName = null
        this.form.currentLiningScheme = null

        // 查询项目器具列表
        this.getProjectMaterialsList(projectId)

        // 查询项目关联的仓库列表
        this.getProjectWarehouseList(projectId)
      } else {
        this.form.companyId = null
        this.form.currentProjectCode = null
        this.form.currentProjectName = null
        this.form.materialCode = null
        this.form.materialName = null
        this.form.currentMaterialCode = null
        this.form.currentMaterialName = null
        this.form.currentLiningScheme = null
        this.materialOptions = []
        this.projectWarehouseList = []
      }
    },

    /** 器具编码选择变化处理 */
    handleMaterialCodeChange(materialCode) {
      if (materialCode) {
        // 根据选择的编码找到对应的器具信息
        const selectedMaterial = this.materialOptions.find(
          material => material.containerMaterialCode === materialCode
        )
        if (selectedMaterial) {
          // 自动填充器具名称
          this.form.materialName = selectedMaterial.containerMaterialName
        }
      } else {
        // 清空器具名称
        this.form.materialName = null
      }

      // 清空当前物料信息
      this.form.currentMaterialCode = null
      this.form.currentMaterialName = null
      this.form.currentLiningScheme = null
    },

    /** 获取项目器具列表 */
    getProjectMaterialsList(projectId) {
      this.materialLoading = true
      getProjectMaterials(projectId).then(response => {
        this.materialOptions = response.data || []
      }).catch(() => {
        this.$modal.msgError('获取项目器具列表失败')
        this.materialOptions = []
      }).finally(() => {
        this.materialLoading = false
      })
    },

    /** 获取项目关联的仓库列表 */
    getProjectWarehouseList(projectId) {
      getProjectWarehouses(projectId).then(response => {
        console.log('项目仓库API返回数据:', response)
        if (response.data && response.data.rows) {
          // 转换为下拉选择需要的格式
          this.projectWarehouseList = response.data.rows.map(item => {
            return {
              warehouseId: item.warehouseId,
              warehouseName: item.warehouseName
            }
          })
          console.log('处理后的仓库列表:', this.projectWarehouseList)
        } else if (response.rows) {
          // 直接使用response.rows
          this.projectWarehouseList = response.rows.map(item => {
            return {
              warehouseId: item.warehouseId,
              warehouseName: item.warehouseName
            }
          })
          console.log('处理后的仓库列表(直接使用rows):', this.projectWarehouseList)
        } else {
          console.log('未找到有效的仓库数据')
          this.projectWarehouseList = []
        }
      }).catch((error) => {
        console.error('获取项目关联仓库列表失败:', error)
        this.$modal.msgError('获取项目关联仓库列表失败')
        this.projectWarehouseList = []
      })
    },

    /** 查询定位器列表 */
    getLocatorList() {
      this.locatorLoading = true
      // 查询所有可用的定位器（包括已绑定和未绑定的）
      listLocatorForBind({ locatorStatus: '1' }).then(response => {
        this.locatorList = response.rows || []
        this.filteredLocatorList = this.locatorList
        this.locatorLoading = false
      }).catch(() => {
        this.locatorLoading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        containerId: null,
        containerCode: null,
        materialCode: null,
        materialName: null,
        companyId: null,
        productionDate: null,
        locatorId: null,
        currentWarehouseId: null,
        locationStatus: '1',
        businessStatus: '1',
        currentProjectId: null,
        currentProjectCode: null,
        currentProjectName: null,
        currentMaterialCode: null,
        currentMaterialName: null,
        currentMaterialQuantity: null,
        currentLiningScheme: null,
        remark: null
      }
      // 清空器具选项列表
      this.materialOptions = []
      this.projectWarehouseList = [] // 清空项目关联仓库列表
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log('=== 选中变化调试信息 ===')
      console.log('选中的数据:', selection)
      console.log('选中数量:', selection.length)

      this.ids = selection.map(item => item.containerId)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      console.log('设置的IDs:', this.ids)
      console.log('single状态:', this.single)
      console.log('multiple状态:', this.multiple)
      console.log('=== 选中调试信息结束 ===')
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加器具'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const containerId = row.containerId || this.ids
      getContainer(containerId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改器具'

        // 如果有当前项目，加载项目的器具列表
        if (this.form.currentProjectId) {
          this.getProjectMaterialsList(this.form.currentProjectId)
          // 加载项目关联的仓库列表
          this.getProjectWarehouseList(this.form.currentProjectId)
        }
      })
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const containerId = row.containerId
      getContainer(containerId).then(response => {
        this.detailForm = response.data
        this.detailOpen = true
        // 设置当前器具ID到各个查询参数中
        this.operationQueryParams.containerId = containerId
        this.transferQueryParams.containerId = containerId
        this.locationQueryParams.containerId = containerId
      })
    },
    /** 详情抽屉打开时的处理 */
    handleDetailOpen() {
      // 重置标签页到基本信息
      this.activeTab = 'basic'
      // 重置分页参数
      this.resetHistoryParams()
    },
    /** 重置历史记录查询参数 */
    resetHistoryParams() {
      this.operationQueryParams.pageNum = 1
      this.operationList = []
      this.operationTotal = 0

      this.transferQueryParams.pageNum = 1
      this.transferList = []
      this.transferTotal = 0

      this.locationQueryParams.pageNum = 1
      this.locationList = []
      this.locationTotal = 0
    },
    /** 获取操作记录列表 */
    getOperationList() {
      if (!this.operationQueryParams.containerId) return

      this.operationLoading = true
      listOperationLog(this.operationQueryParams).then(response => {
        this.operationList = this.processOperationData(response.rows)
        this.operationTotal = response.total
        this.operationLoading = false
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        const mockData = [
          {
            operationTime: new Date('2024-01-15 10:30:00'),
            operationType: '1', // 新增
            createBy: 'zhangsan',
            warehouse: { warehouseName: '华东中央库房' },
            operationDetail: '器具新增操作，初始化器具信息',
            remark: '系统新增'
          },
          {
            operationTime: new Date('2024-01-14 15:20:00'),
            operationType: '2', // 定位器绑定
            createBy: 'lisi',
            warehouse: { warehouseName: '华东中央库房' },
            operationDetail: '为器具绑定定位器设备LOC001',
            remark: '设备绑定'
          },
          {
            operationTime: new Date('2024-01-13 14:45:00'),
            operationType: '6', // 装箱
            createBy: 'wangwu',
            warehouse: { warehouseName: '华东中央库房' },
            operationDetail: '器具装箱操作，装载物料：电子元件',
            remark: '满箱装载'
          },
          {
            operationTime: new Date('2024-01-12 11:30:00'),
            operationType: '4', // 清洗
            createBy: 'zhaoliu',
            warehouse: { warehouseName: '华东中央库房' },
            operationDetail: '器具清洗维护，清洗完成',
            remark: '定期清洗'
          },
          {
            operationTime: new Date('2024-01-11 09:15:00'),
            operationType: '11', // 检查
            createBy: 'qianqi',
            warehouse: { warehouseName: '华东中央库房' },
            operationDetail: '器具质量检查，状态良好',
            remark: '例行检查'
          }
        ]

        this.operationList = this.processOperationData(mockData)
        this.operationTotal = mockData.length
        this.operationLoading = false
      })
    },
    /** 处理操作记录数据 */
    processOperationData(data) {
      return data.map(item => {
        // 确保数据结构的兼容性
        return {
          ...item,
          // 如果后端返回的是 operatorName 字段，则映射到 createBy
          createBy: item.createBy || item.operatorName || '-',
          // 确保 warehouse 对象存在
          warehouse: item.warehouse || { warehouseName: item.warehouseName || '-' },
          // 如果后端返回的是 operationDescription 字段，则映射到 operationDetail
          operationDetail: item.operationDetail || item.operationDescription || '-'
        }
      })
    },
    /** 获取移库记录列表 */
    getTransferList() {
      if (!this.transferQueryParams.containerId) return

      this.transferLoading = true
      listTransferRecord(this.transferQueryParams).then(response => {
        this.transferList = response.rows
        this.transferTotal = response.total
        this.transferLoading = false
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        const mockData = [
          {
            sourceWarehouseName: '华北库房',
            targetWarehouseName: '华东中央库房',
            materialCode: 'MAT001',
            materialName: '电子元件A型',
            projectCode: 'PRJ2024001',
            projectName: '智能制造项目一期',
            operatorName: '赵六',
            transferStatus: '2', // 1-进行中 2-已完成 3-已取消
            createTime: new Date('2024-01-12 14:30:00'),
            updateTime: new Date('2024-01-12 16:45:00')
          },
          {
            sourceWarehouseName: '华南库房',
            targetWarehouseName: '华北库房',
            materialCode: 'MAT002',
            materialName: '精密仪器配件',
            projectCode: 'PRJ2024002',
            projectName: '自动化生产线改造',
            operatorName: '钱七',
            transferStatus: '2',
            createTime: new Date('2024-01-10 11:20:00'),
            updateTime: new Date('2024-01-10 15:30:00')
          },
          {
            sourceWarehouseName: '华东中央库房',
            targetWarehouseName: '华南库房',
            materialCode: 'MAT003',
            materialName: '工业传感器',
            projectCode: 'PRJ2024003',
            projectName: '物联网监控系统',
            operatorName: '孙八',
            transferStatus: '1',
            createTime: new Date('2024-01-15 09:15:00'),
            updateTime: new Date('2024-01-15 09:15:00')
          }
        ]

        this.transferList = mockData
        this.transferTotal = mockData.length
        this.transferLoading = false
      })
    },
    /** 获取定位日志列表 */
    getLocationList() {
      if (!this.locationQueryParams.containerId) return

      this.locationLoading = true
      listLocationLog(this.locationQueryParams).then(response => {
        this.locationList = response.rows
        this.locationTotal = response.total
        this.locationLoading = false
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        const mockData = [
          {
            createTime: new Date('2024-01-15 16:45:00'),
            longitude: '121.4737',
            latitude: '31.2304',
            uploadAddress: '上海市浦东新区张江高科技园区',
            temperature: 23.5,
            humidity: 65,
            shockLevel: 'Level 2',
            batteryLevel: 78
          },
          {
            createTime: new Date('2024-01-15 12:30:00'),
            longitude: '121.4690',
            latitude: '31.2280',
            uploadAddress: '上海市浦东新区世纪大道',
            temperature: 25.2,
            humidity: 58,
            shockLevel: 'Level 1',
            batteryLevel: 80
          },
          {
            createTime: new Date('2024-01-15 08:15:00'),
            longitude: '121.4650',
            latitude: '31.2250',
            uploadAddress: '上海市浦东新区陆家嘴金融区',
            temperature: 22.8,
            humidity: 72,
            shockLevel: 'Level 3',
            batteryLevel: 82
          },
          {
            createTime: new Date('2024-01-14 20:30:00'),
            longitude: '121.4580',
            latitude: '31.2200',
            uploadAddress: '上海市浦东新区外滩金融中心',
            temperature: 24.1,
            humidity: 60,
            shockLevel: 'Level 1',
            batteryLevel: 85
          },
          {
            createTime: new Date('2024-01-14 14:15:00'),
            longitude: '121.4720',
            latitude: '31.2350',
            uploadAddress: '上海市浦东新区科技园区物流中心',
            temperature: 26.3,
            humidity: 55,
            shockLevel: 'Level 2',
            batteryLevel: 88
          }
        ]

        this.locationList = mockData
        this.locationTotal = mockData.length
        this.locationLoading = false
      })
    },
    /** 获取操作类型名称 */
    getOperationTypeName(type) {
      const typeMap = {
        '1': '新增',
        '2': '定位器绑定',
        '3': '定位器解绑',
        '4': '清洗',
        '5': '折叠整理',
        '6': '装箱',
        '7': '拆箱',
        '8': '封存',
        '9': '解封',
        '10': '维修',
        '11': '检查'
      }
      return typeMap[type] || '未知'
    },
    /** 获取操作类型标签样式 */
    getOperationTypeTag(type) {
      const tagMap = {
        '1': 'success',   // 新增
        '2': 'primary',   // 定位器绑定
        '3': 'warning',   // 定位器解绑
        '4': 'info',      // 清洗
        '5': '',          // 折叠整理
        '6': 'primary',   // 装箱
        '7': 'danger',    // 拆箱
        '8': 'info',      // 封存
        '9': 'success',   // 解封
        '10': 'warning',  // 维修
        '11': ''          // 检查
      }
      return tagMap[type] || ''
    },
    /** 获取移库状态名称 */
    getTransferStatusName(status) {
      const statusMap = {
        '1': '进行中',
        '2': '已完成',
        '3': '已取消'
      }
      return statusMap[status] || '未知'
    },
    /** 获取移库状态标签样式 */
    getTransferStatusTag(status) {
      const tagMap = {
        '1': 'warning',  // 进行中
        '2': 'success',  // 已完成
        '3': 'danger'    // 已取消
      }
      return tagMap[status] || ''
    },
    /** 标签页切换处理 */
    handleTabClick(tab) {
      const tabName = tab.name
      console.log('=== 标签页切换调试 ===')
      console.log('切换到标签页:', tabName)
      console.log('当前定位数据长度:', this.locationList.length)

      if (tabName === 'operation' && this.operationList.length === 0) {
        this.getOperationList()
      } else if (tabName === 'transfer' && this.transferList.length === 0) {
        this.getTransferList()
      } else if ((tabName === 'location' || tabName === 'track') && this.locationList.length === 0) {
        console.log('加载定位数据...')
        this.getLocationList()
      }
    },
    /** 提交按钮 */
    submitForm() {
      // 表单验证已在子组件中完成，这里直接处理提交逻辑
      console.log('提交前form数据:', this.form)

      if (this.form.containerId != null) {
        // 修改器具
        updateContainer(this.form).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        }).catch(error => {
          console.error('修改器具失败:', error)
          this.$modal.msgError('修改失败，请重试')
        })
      } else {
        // 新增器具
        addContainer(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        }).catch(error => {
          console.error('新增器具失败:', error)
          this.$modal.msgError('新增失败，请重试')
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const containerIds = row.containerId || this.ids
      this.$modal.confirm('是否确认删除器具编号为"' + containerIds + '"的数据项？').then(function() {
        return delContainer(containerIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pack/container/export', {
        ...this.queryParams
      }, `container_${new Date().getTime()}.xlsx`)
    },
    /** 绑定定位器按钮操作 */
    handleBindLocator(row) {
      console.log('=== 绑定定位器调试信息 ===')
      console.log('传入的row参数:', row)
      console.log('row参数类型:', typeof row)
      console.log('当前选中的IDs:', this.ids)
      console.log('当前器具列表长度:', this.containerList.length)

      // 如果传入的row是业务数据（有containerId属性），则使用它
      // 否则从选中的列表中获取
      let containerData = null

      if (row && row.containerId) {
        // 从表格行操作传入的业务数据
        containerData = row
        console.log('使用传入的行数据:', containerData)
      } else {
        // 从顶部按钮调用，使用选中的数据
        if (this.ids.length !== 1) {
          console.log('错误：请选择一个器具，当前选中数量:', this.ids.length)
          this.$modal.msgError('请选择一个器具进行绑定')
          return
        }

        const selectedId = this.ids[0]
        containerData = this.containerList.find(item => item.containerId === selectedId)
        console.log('从列表中查找器具，ID:', selectedId, '找到的数据:', containerData)
      }

      if (!containerData) {
        console.log('错误：未找到器具信息')
        this.$modal.msgError('未找到器具信息')
        return
      }

      this.bindForm = {
        containerId: containerData.containerId,
        containerCode: containerData.containerCode,
        locatorIds: []
      }

      console.log('设置的绑定表单数据:', this.bindForm)
      console.log('=== 调试信息结束 ===')

      this.locatorSearchText = ''
      this.getLocatorList()
      this.bindOpen = true
    },
    /** 解绑定位器按钮操作 */
    handleUnbindLocator(eventOrRow) {
      // 获取要解绑的器具列表
      let containerIds = []
      let containerCodes = []

      // 判断参数是否为业务数据行（包含containerId）还是点击事件
      if (eventOrRow && eventOrRow.containerId) {
        // 单个器具操作（从表格行传入）
        containerIds = [eventOrRow.containerId]
        containerCodes = [eventOrRow.containerCode]
      } else {
        // 批量操作（从顶部按钮调用，eventOrRow是点击事件对象）
        containerIds = this.ids
        containerCodes = this.ids.map(id => {
          const container = this.containerList.find(item => item.containerId === id)
          return container ? container.containerCode : id
        })
      }

      if (containerIds.length === 0) {
        this.$modal.msgError('请选择要解绑的器具')
        return
      }

      // 构建确认消息
      let message = ''
      if (containerIds.length === 1) {
        message = `是否确认解绑器具"${containerCodes[0]}"的定位器？`
      } else {
        message = `是否确认解绑以下 ${containerIds.length} 个器具的定位器？\n${containerCodes.join('、')}`
      }

      this.$modal.confirm(message).then(() => {
        // 批量解绑
        const unbindPromises = containerIds.map(containerId => unbindLocator(containerId))

        return Promise.all(unbindPromises)
      }).then(() => {
        this.getList()
        if (containerIds.length === 1) {
          this.$modal.msgSuccess('解绑成功')
        } else {
          this.$modal.msgSuccess(`成功解绑 ${containerIds.length} 个器具的定位器`)
        }
      }).catch(() => {
        // 错误处理已在请求拦截器中处理
      })
    },
    /** 提交绑定表单 */
    submitBindForm() {
      // 表单验证已在子组件中完成，这里直接处理业务逻辑
      batchBindLocators(this.bindForm.containerId, this.bindForm.locatorIds).then(response => {
        this.$modal.msgSuccess(`成功绑定 ${this.bindForm.locatorIds.length} 个定位器`)
        this.bindOpen = false
        this.getList()
      }).catch(error => {
        console.error('绑定定位器失败:', error)
        this.$modal.msgError('绑定失败，请重试')
      })
    },
    /** 当前物料编码选择变化处理 */
    handleCurrentMaterialCodeChange(materialCode) {
      if (materialCode) {
        // 根据选择的编码找到对应的物料信息
        const selectedMaterial = this.materialOptions.find(
          material => material.materialCode === materialCode
        )
        if (selectedMaterial) {
          // 自动填充物料名称
          this.form.currentMaterialName = selectedMaterial.materialName
          // 自动填充内衬方案
          this.form.currentLiningScheme = selectedMaterial.liningScheme || ''
        }
      } else {
        // 清空物料名称和内衬方案
        this.form.currentMaterialName = null
        this.form.currentLiningScheme = null
      }
    },

    /** 获取器具显示文本 */
    getContainerDisplayText() {
      if (!this.bindForm.containerId) {
        return ''
      }

      const container = this.containerList.find(item => item.containerId === this.bindForm.containerId)
      if (!container) {
        return this.bindForm.containerCode || ''
      }

      return `${container.containerCode} - ${container.materialName || container.materialCode || ''}`
    },

    /** 定位器搜索处理 */
    handleLocatorSearch() {
      this.filterLocators()
    },

    /** 过滤定位器列表 */
    filterLocators() {
      if (!this.locatorSearchText) {
        this.filteredLocatorList = this.locatorList
        return
      }

      const searchText = this.locatorSearchText.toLowerCase()
      this.filteredLocatorList = this.locatorList.filter(locator => {
        return (
          locator.locatorCode.toLowerCase().includes(searchText) ||
          (locator.deviceModel && locator.deviceModel.toLowerCase().includes(searchText))
        )
      })
    }
  }
}
</script>

<style scoped>
/* 主页面样式 */
</style>
